﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using System.Data;
using System.Security;
using System.Threading;
using System.Security.Principal;
using System.DirectoryServices;

namespace Billder
{
    public partial class PartMaster : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("Account/login.aspx");
            }
             
            if(User.IsInRole("ETTO\\PartCreator"))Response.Write("<h1>si</h1>");
            switch (txtAction.Value)
            {
                case "prepareEdit":
                    txtAction.Value = "commitEdit";
                    prepareEdit();
                    extraFields();
                    break;
                case "none":
                    ///extraFields();
                    txtAction.Value = "new";
                    ClearForm();
                    break;
                case "UploadImage":
                    uploadImage();
                    break;
                case "commitEdit":
                    
                    commitEdit();
                    break;
                case "new":
                    AddPartMaster();
                    ClearForm();
                    break;
            }
           
            ShowTable();
        }

        private void prepareEdit()
        {
            DataTable dt = Catalog.get("PartMaster", int.Parse(txtPNID.Value));
            txtAdders.Text = dt.Rows[0]["Adders"].ToString();
            txtDescription.Text = dt.Rows[0]["Description"].ToString();
            txtDistributor.Text = dt.Rows[0]["Distributor"].ToString();
            txtFKDistributor.Value = dt.Rows[0]["FKDistributor"].ToString();
            txtFKManufacturer.Value = dt.Rows[0]["FKManufacturer"].ToString();
            txtImgCode.Value = "";
            txtManufacturer.Text = dt.Rows[0]["Manufacturer"].ToString();
            txtManufacturerPartNumber.Text = dt.Rows[0]["ManufacturerPartNumber"].ToString();
            txtPartNumber.Text = dt.Rows[0]["PartNumber"].ToString();
            txtPNID.Value = dt.Rows[0]["PKPartMaster"].ToString();
            txtPurchacePrice.Text = dt.Rows[0]["PurchacePrice"].ToString();
            txtPurchaseQty.Text = dt.Rows[0]["PurchaseQty"].ToString();
            txtSalesMultiple.Text = dt.Rows[0]["SalesQty"].ToString();
            txtSalesPrice.Text = dt.Rows[0]["SalesPrice"].ToString();
            txtStatus.Value = dt.Rows[0]["FKStatus"].ToString();
            partImg.Src = "Images/" + dt.Rows[0]["Photo"].ToString();
        }

        private void extraFields()
        {
            if (User.Identity.Name.Equals("Demetrio"))
            {
                txtSalesMultiple.Enabled = true;
                txtSalesMultiple.CssClass = txtSalesMultiple.CssClass.Replace("disabled", "");
                txtSalesPrice.Enabled = true;
                txtSalesPrice.CssClass = txtSalesPrice.CssClass.Replace("disabled", "");
                btnApprove.Enabled = true;
                btnReject.Enabled = true;
            }
            else
            {
                txtSalesMultiple.Enabled = false;
                txtSalesMultiple.CssClass += txtSalesMultiple.CssClass.Contains("disabled") ? "" : " disabled";
                txtSalesPrice.Enabled = false;
                txtSalesPrice.CssClass += txtSalesPrice.CssClass.Contains("disabled") ? "" : " disabled";
                btnApprove.Enabled = false;
                btnReject.Enabled = false;
            }
        }

        private void ClearForm()
        {
            foreach (Control control in txtAction.Parent.Controls)
            {
                if (control is TextBox)
                {
                    ((TextBox)control).Text = "";
                }


            }
        }

        private void ShowTable()
        {
            List<OColumn> columns = new List<OColumn>();
            columns.Add(new OColumn("PartNumber") { label = "No. Parte" });
            columns.Add(new OColumn("ManufacturerPartNumber") { label = "NP Manuf." });
            columns.Add(new OColumn("Description") { label = "Descripcion" });
            columns.Add(new OColumn("Manufacturer") { label = "Manufacturero" });
            columns.Add(new OColumn("Distributor") { label = "Distribuidor" });
            columns.Add(new OColumn("PurchacePrice") { label = "Precio Compra" });
            columns.Add(new OColumn("DatasheetLink") { label = "Datasheet" });
            columns.Add(new OColumn("QuoteLink") { label = "Cotizacion" });
            columns.Add(new OColumn("SalesPrice") { label = "Precio Venta" });
            columns.Add(new OColumn("SalesQty") { label = "Multiplo Venta" });
            columns.Add(new OColumn("PhotoLink") { label = "Foto" });
            OTable t = new OTable("sp_cat_GetPartMaster", columns);
            divList.Controls.Add(t.getTable("PKPartMaster DESC","FKStatus NOT IN (2,5)", "PKPartMaster"));
        }
        private int AddPartMaster()
        {
            return AddPartMaster("1");
        }
        private int AddPartMaster( string status )
        {
            File.Move(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value, System.Configuration.ConfigurationManager.AppSettings["imagesDir"] + txtImgCode.Value);
            string quotesDir = System.Configuration.ConfigurationManager.AppSettings["quotesDir"];
            string quoteFileName = txtQuote.PostedFile.FileName;
            string newQuoteFileName = Guid.NewGuid().ToString() + quoteFileName.Substring(quoteFileName.LastIndexOfAny("\\/".ToCharArray()) + 1);
            string newQuoteFileNameWithDir = quotesDir + newQuoteFileName;
            txtQuote.PostedFile.SaveAs(newQuoteFileNameWithDir);
            string DatasheetsDir = System.Configuration.ConfigurationManager.AppSettings["dataSheetsDir"];
            string DatasheetFileName = txtDatasheet.PostedFile.FileName;
            string newDatasheetFileName = Guid.NewGuid().ToString() + DatasheetFileName.Substring(DatasheetFileName.LastIndexOfAny("\\/".ToCharArray()) + 1);
            string newDatasheetFileNameWithDir = DatasheetsDir + newDatasheetFileName;
            txtDatasheet.PostedFile.SaveAs(newDatasheetFileNameWithDir);
            HandleAutocompletes();
            Hashtable ht = new Hashtable();
            ht.Add("PKPartMaster", "0");
            ht.Add("FKManufacturer", txtFKManufacturer.Value);
            ht.Add("FKDistributor", txtFKDistributor.Value);
            ht.Add("FKStatus", status);
            ht.Add("PartNumber", txtPartNumber.Text);
            ht.Add("ManufacturerPartNumber", txtManufacturerPartNumber.Text);
            ht.Add("Description", txtDescription.Text);
            ht.Add("PurchacePrice", txtPurchacePrice.Text);
            ht.Add("PurchaseQty", txtPurchaseQty.Text);
            ht.Add("SalesPrice", null);
            ht.Add("SalesQty", null);
            ht.Add("Adders", txtAdders.Text);
            ht.Add("DataSheet", newDatasheetFileName);
            ht.Add("Photo", txtImgCode.Value);
            ht.Add("Quote", newQuoteFileName);
            ht.Add("UpdatedBy", 1);
            int pk = Catalog.add("PartMaster", ht);
            return pk;
        }
        private void commitEdit()
        {
            string quotesDir;
            string quoteFileName;
            string newQuoteFileName = null;
            string newQuoteFileNameWithDir;
            string DatasheetsDir;
            string DatasheetFileName;
            string newDatasheetFileName= null;
            string newDatasheetFileNameWithDir;
            string originalPK = txtPNID.Value;
            int backup;
            string status = txtStatus.Value.Equals("1")|| txtStatus.Value.Equals("2")? "1" : "4";
            Hashtable ht = new Hashtable();

            if (!(txtStatus.Value.Equals("1") || txtStatus.Value.Equals("2") ))
            {
                ht.Add("PKPartCopy", txtPNID.Value);
                ht.Add("UpdatedBy", "1");
                backup = Catalog.add("PartCopy", ht);
                status = null;
            }
            if (!txtImgCode.Value.Equals(""))
            {
                File.Move(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value, System.Configuration.ConfigurationManager.AppSettings["imagesDir"] + txtImgCode.Value);
            }
            else { txtImgCode.Value=""; }
            if (txtQuote.HasFile)
            {
                quotesDir = System.Configuration.ConfigurationManager.AppSettings["quotesDir"];
                quoteFileName = txtQuote.PostedFile.FileName;
                newQuoteFileName = Guid.NewGuid().ToString() + quoteFileName.Substring(quoteFileName.LastIndexOfAny("\\/".ToCharArray()) + 1);
                newQuoteFileNameWithDir = quotesDir + newQuoteFileName;
                txtQuote.PostedFile.SaveAs(newQuoteFileNameWithDir);
            }
            if (txtDatasheet.HasFile)
            {
                DatasheetsDir = System.Configuration.ConfigurationManager.AppSettings["dataSheetsDir"];
                DatasheetFileName = txtDatasheet.PostedFile.FileName;
                newDatasheetFileName = Guid.NewGuid().ToString() + DatasheetFileName.Substring(DatasheetFileName.LastIndexOfAny("\\/".ToCharArray()) + 1);
                newDatasheetFileNameWithDir = DatasheetsDir + newDatasheetFileName;
                txtDatasheet.PostedFile.SaveAs(newDatasheetFileNameWithDir);
            }
            HandleAutocompletes();
            ht = new Hashtable();
            ht.Add("PKPartMaster", txtPNID.Value);
            ht.Add("FKManufacturer", txtFKManufacturer.Value);
            ht.Add("FKDistributor", txtFKDistributor.Value);
            ht.Add("FKStatus", status);
            ht.Add("PartNumber", txtPartNumber.Text);
            ht.Add("ManufacturerPartNumber", txtManufacturerPartNumber.Text);
            ht.Add("Description", txtDescription.Text);
            ht.Add("PurchacePrice", txtPurchacePrice.Text);
            ht.Add("PurchaseQty", txtPurchaseQty.Text);
            ht.Add("SalesPrice", txtSalesPrice.Text.Equals("") ? null : txtSalesPrice.Text);
            ht.Add("SalesQty", txtSalesMultiple.Text.Equals("") ? null : txtSalesMultiple.Text);
            ht.Add("Adders", txtAdders.Text);
            ht.Add("DataSheet", newDatasheetFileName);
            ht.Add("Photo", txtImgCode.Value.Equals("")?null: txtImgCode.Value);
            ht.Add("Quote", newQuoteFileName);
            ht.Add("UpdatedBy", "1");
            int pk = Catalog.add("PartMaster", ht);
        }

        private void HandleAutocompletes()
        {
            if (txtFKManufacturer.Value == "0")
            {
                Hashtable manufacturerHT = new Hashtable();
                manufacturerHT.Add("Manufacturer", txtManufacturer.Text.Trim());
                manufacturerHT.Add("UserUpdater", "1");
                int fkMan = Catalog.add("Manufacturer", manufacturerHT);
                txtFKManufacturer.Value = fkMan.ToString();
            }
            if (txtFKDistributor.Value == "0")
            {
                Hashtable DistributorHT = new Hashtable();
                DistributorHT.Add("Distributor", txtDistributor.Text.Trim());
                DistributorHT.Add("UserUpdater", "1");
                int fkDis = Catalog.add("Distributor", DistributorHT);

                txtFKDistributor.Value = fkDis.ToString();
            }
        }
        protected void uploadImage()
        {
            Request.Files["partImageFile"].SaveAs(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value + Request.Files["partImageFile"].FileName);
            Response.Clear();
            Response.Write("SUCCESS");
            Response.Write("<script>parent.refreshImg('" + txtImgCode.Value + Request.Files["partImageFile"].FileName + "');</script>");
            Response.End();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();
            ht.Add("PKPartMaster", txtPNID.Value);
            ht.Add("FKManufacturer", null);
            ht.Add("FKDistributor", null);
            ht.Add("FKStatus", "3");
            ht.Add("PartNumber", null);
            ht.Add("ManufacturerPartNumber", null);
            ht.Add("Description", null);
            ht.Add("PurchacePrice",null);
            ht.Add("PurchaseQty", null);
            ht.Add("SalesPrice",  txtSalesPrice.Text);
            ht.Add("SalesQty", txtSalesMultiple.Text);
            ht.Add("Adders", null);
            ht.Add("DataSheet", null);
            ht.Add("Photo",null);
            ht.Add("Quote", null);
            ht.Add("UpdatedBy", "1");
            int pk = Catalog.add("PartMaster", ht);
            ht = new Hashtable();
            ht.Add("PKPartCopy", txtPNID.Value);
            ht.Add("UpdatedBy", null);
            Catalog.removeCopy("Part" , ht);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {   Hashtable ht = new Hashtable();
            ht.Add("PKPartCopy", txtPNID.Value);
            ht.Add("UpdatedBy", "1");
            Catalog.reject("Part", ht);
        }
        
    }
}